package com.jay.aigcoj.bot.ds;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

//java单纯调用DS
@Component
public class DSApi {

    private Gson gson = new Gson();

    private String key = "sk-1fb561dd09a6445fbb10129659e834c7";

    public String sendDeepseekChat(String question) throws UnirestException {

        Unirest.setTimeouts(0, 0);
        List<DSRequest.Message> messages = new ArrayList<>();
        messages.add(DSRequest.Message.builder().role("system")
                .content("你是一个OJ判题系统的机器人，擅长程序设计与算法")
                .build());
        messages.add(DSRequest.Message.builder().role("user").content(question).build());
        DSRequest requestBody = DSRequest.builder()
                .model("deepseek-chat")
                .messages(messages)
                .build();
        HttpResponse<String> res = Unirest.post("https://api.deepseek.com/chat/completions")
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .header("Authorization", "Bearer " + key)
                .body(gson.toJson(requestBody))
                .asString();
        // 解析响应
        if (res.getStatus() == 200) {
            String responseBody = res.getBody();
            JsonObject jsonResponse = JsonParser.parseString(responseBody).getAsJsonObject();
            String content = jsonResponse.getAsJsonArray("choices")
                    .get(0).getAsJsonObject()
                    .getAsJsonObject("message")
                    .get("content").getAsString();
            return content;
        } else {
            throw new RuntimeException("请求失败，状态码: " + res.getStatus());
        }
    }
}